import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

/// 视频预览页面
class VideoViewerPage extends StatefulWidget {
  final String url;

  const VideoViewerPage({Key? key, required this.url}) : super(key: key);

  @override
  VideoViewerPageState createState() => VideoViewerPageState();
}

class VideoViewerPageState extends State<VideoViewerPage> {
  /// 视频控制器
  VideoPlayerController? _videoPlayerController;

  /// 是否正在播放
  bool _isPlaying = false;


  @override
  void initState() {
    debugPrint("视频播放地址 = ${widget.url}");
    super.initState();
    //视频加载完成后，自动播放
    _videoPlayerController = VideoPlayerController.network(widget.url)
      ..initialize().then((_) {
        setState(() {
          _videoPlayerController!.play();
        });
      });

    //设置播放状态监听
    _videoPlayerController!.addListener(() {
      setState(() {
        _isPlaying = _videoPlayerController!.value.isPlaying;
      });
    });
  }

  @override
  void dispose() {
    //销毁控制器
    _videoPlayerController?.dispose();
    super.dispose();
  }

  /// 构建播放界面
  Widget _buildPlayerWidget() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
          onTap: () {
            if (_isPlaying) {
              _videoPlayerController!.pause();
            }
          },
          child: Container(
            constraints: BoxConstraints(
                maxWidth: 0.5 * MediaQuery.of(context).size.height),
            child: AspectRatio(
              aspectRatio: _videoPlayerController!.value.aspectRatio,
              child: VideoPlayer(_videoPlayerController!),
            ),
          ),
        ),
        //进度条
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            //滑块颜色
            thumbColor: Colors.transparent,
            //滑块拖拽时外圈的颜色
            overlayColor: Colors.transparent,
            //进度条高度
            trackHeight: 3.0,
          ),
          child: Slider(
            max: _videoPlayerController!.value.duration.inMilliseconds
                .truncateToDouble(),
            value: _videoPlayerController!.value.position.inMilliseconds
                .truncateToDouble(),
            //进度条滑块左边颜色
            activeColor: Colors.white.withOpacity(0.8),
            //进度条滑块右边颜色
            inactiveColor: Colors.white.withOpacity(0.2),
            //进度改变时回调
            onChanged: (double value) {
              //拖动进度
              _videoPlayerController!.seekTo(
                Duration(
                  milliseconds: value.truncate(),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  /// 构建加载圈
  Widget _buildLoadingWidget() {
    return Center(
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation(Colors.white.withOpacity(0.7)),
        backgroundColor: Colors.white.withOpacity(0.4),
      ),
    );
  }

  /// 构建可播放按钮
  Widget _buildCanPlayBtn() {
    if (_videoPlayerController!.value.isInitialized && !_isPlaying) {
      return Center(
        child: GestureDetector(
          onTap: () {
            _videoPlayerController!.play();
          },
          child: const Center(
            child: Icon(
              Icons.play_circle_fill_outlined,
              color: Colors.white,
              size: 80.0,
            ),
          ),
        ),
      );
    } else {
      return Container();
    }
  }

  /// 构建关闭按钮
  Widget _buildCloseBtn() {
    return InkWell(
      onTap: () {
        Navigator.pop(context);
      },
      child: const Icon(
        Icons.cancel,
        color: Colors.white,
        size: 40.0,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          //根据视频是否初始化，决定显示播放界面还是加载界面
          _videoPlayerController!.value.isInitialized
              ? _buildPlayerWidget()
              : _buildLoadingWidget(),
          //关闭按钮
          Positioned(
            left: 30.0,
            top: 50.0,
            child: _buildCloseBtn(),
          ),
          //未播放时，显示可播放按钮
          _buildCanPlayBtn()
        ],
      ),
    );
  }
}
